package Demo1;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import javax.xml.stream.events.DTD;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet({"/dept/list","/dept/detail","/dept/save","/dept/delete","/dept/modify"})
public class DeptServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 先检session对象中是否有登录信息
        HttpSession httpSession = req.getSession(false);
         if(httpSession!=null&&httpSession.getAttribute("User")!=null){
             // 获取 servlet 路径
             String path = req.getServletPath();
             // 执行对应的方法
             if ("/dept/list".equals(path)) {
                 doList(req, resp);
             } else if ("/dept/detail".equals(path)) {
                 doDetail(req, resp);
             } else if ("/dept/save".equals(path)) {
                 doSave(req, resp);
             } else if ("/dept/delete".equals(path)) {
                 doDel(req, resp);
             } else if ("/dept/modify".equals(path)) {
                 doModify(req, resp);
             }
         } else{
             resp.sendRedirect(req.getContextPath()+"/index.jsp");
        }
    }


    /**
     * 修改数据
     * @param req
     * @param resp
     * @throws IOException
     * @throws ServletException
     */
    private void doModify(HttpServletRequest req, HttpServletResponse resp) throws IOException,ServletException {
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        // 获取表单中已经修改过的数据
        String deptno = req.getParameter("deptno");
        String dname = req.getParameter("dname");
        String loc = req.getParameter("loc");

        int count = 0;
        // 获取数据库中的数据并将对应的值进行修改
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        String sql = "update dept set dname =?,loc = ? where deptno = ?";

        try {
            connection = DBUtil.getConnection();
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, dname);
            preparedStatement.setString(2, loc);
            preparedStatement.setString(3, deptno);
            count = preparedStatement.executeUpdate();

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(connection, preparedStatement, null);
        }
        // 检测是否修改成功
        if (count == 1) {
            resp.sendRedirect(req.getContextPath() + "/dept/list");
        }
    }

    /**
     *删除其中一条数据
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    private void doDel(HttpServletRequest req, HttpServletResponse resp) throws ServletException,IOException{
        // 获取前端提交的url上的deptno的值
        String deptno = req.getParameter("deptno");

        Connection connection = null;
        PreparedStatement preparedStatement = null;
        // 获取连接
        connection = DBUtil.getConnection();

        //执行sql语句
        String sql = "delete from dept where deptno = ?";
        int count =0;
        try {
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1,deptno);
            count = preparedStatement.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            DBUtil.close(connection,preparedStatement,null);
        }
        if(count==1){
            // 跳转到list,重定向,因为不用携带数据
            String contextpath = req.getContextPath(); // 获取应用的项目名
            resp.sendRedirect(contextpath+"/dept/list");
        }
    }


    /**
     * 保存新增的数据到数据库
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    private void doSave(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");

        // 获取前端提交的数据
        String Deptno = req.getParameter("deptno");
        String Dname = req.getParameter("dname");
        String Loc = req.getParameter("loc");

        // 向数据库中插入数据
        Connection connection = null;
        PreparedStatement preparedStatement = null;

        // 将deptno化作整数插入数据库
        int dno = Integer.parseInt(Deptno);
        int count = 0;
        String sql = "insert into dept(deptno,dname,loc) values(?,?,?)";
        try {
            connection = DBUtil.getConnection();
            preparedStatement = connection.prepareStatement(sql);
            // 设置值
            preparedStatement.setInt(1,dno);
            preparedStatement.setString(2,Dname);
            preparedStatement.setString(3,Loc);

            // 这里的返回值的值是受影响的行数
            count = preparedStatement.executeUpdate();
            System.out.println(count);

        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtil.close(connection,preparedStatement,null);
        }
        if(count==1){
            req.getRequestDispatcher("/dept/list").forward(req,resp);
        }
    }

    /**
     * 根据部门编号获取部门信息
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    private void doDetail(HttpServletRequest req, HttpServletResponse resp)  throws ServletException, IOException {
        String dno = req.getParameter("dno");
        // 获取连接
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        // 获取连接
        connection = DBUtil.getConnection();
        // 执行sql语句
        String sql = "select dname,loc from dept where deptno = ?";
        try {
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1,dno);
            resultSet = preparedStatement.executeQuery();
            if(resultSet.next())
            {
                String dname = resultSet.getString("dname");
                String loc = resultSet.getString("loc");
                // 创建对象
                Dept dept = new Dept(dno,dname,loc);
                // 向请求域中存储对象
                req.setAttribute("Dept",dept);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            DBUtil.close(connection,preparedStatement,resultSet);
        }
        // 转发数据
        String forword = "/"+req.getParameter("flag")+".jsp";
        // 将路径打包转发到对应部分.
        req.getRequestDispatcher(forword).forward(req,resp);
    }

    private void doList(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
     // 查询数据库中的内容
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        // 创建集合
        List<Dept> depts = new ArrayList<>();

        // 获取连接
        connection = DBUtil.getConnection();

        // 执行sql语句
        String sql = "select deptno,dname,loc from dept";


        try {
            // 执行sql语句
            preparedStatement = connection.prepareStatement(sql);

            // 获取查询结果集
            resultSet = preparedStatement.executeQuery();
            // 获取数据库中的值

            while(resultSet.next()){

                String deptno = resultSet.getString("deptno");
                String dname = resultSet.getString("dname");
                String loc = resultSet.getString("loc");

                Dept dept = new Dept(deptno,dname,loc);

                depts.add(dept);
            }
            // 将数据存储在请求域中,接着转发给index.jsp
            req.setAttribute("DeptList",depts);
            // 将数据转发给index.jsp
            req.getRequestDispatcher("/list.jsp").forward(req,resp);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
